import {reqPostUserLogin,reqGetLogout} from '@/api'
import {Message} from 'element-ui'

const state = {
  userInfo:{
    // 存储后获取
    name:localStorage.getItem('name'),
    token:localStorage.getItem('token')
  }
 
}
const actions = {
  // 登录的异步请求
  async userLogin({commit},user){
    console.log('登录异步',user);
    const result = await reqPostUserLogin(user)
    console.log(result);
    if(result.code === 200) {
     
      commit('SAVE_USER_LOGIN',result.data)
      return true
    } else {
      console.log(result.message);
    }
  },

  // 退出登录
  async userLogout({commit}){
    const result = await reqGetLogout()
    console.log(result);
    if(result.code === 200) {
    //  这里是清空本地的存储
    Message.success('退出成功')
      localStorage.removeItem('name')
      localStorage.removeItem('token')

      commit('REMOVE_USER_LOGOUT')
    } else {
      console.log(result.message);
    }
  }
}
const mutations = {
   // 1. 存储用户登陆的内容
  SAVE_USER_LOGIN(state,userInfo){
    state.userInfo.name = userInfo.name
    state.userInfo.token = userInfo.token

    // 为了让用户刷新页面后仍然存在token，所以在本地存储一份
  localStorage.setItem('name',userInfo.name)
  localStorage.setItem('token',userInfo.token)
  },

  // 退出登录，清空token
  REMOVE_USER_LOGOUT(state){
    // 这里清空的是vuex状态中的
    state.userInfo.name = '',
    state.userInfo.token = ''
  }
  
}
const getters = {}

export default {
  namespaced:true,
  state,
  actions,
  mutations,
  getters
}